package springmvc.web.cocktails;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import lombok.Data;

import org.dhbw.cocktail.Cocktail;
import org.dhbw.cocktail.Ingredient;
import org.dhbw.cocktail.UsedIngredient;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

/**
 * Controller for AJAX-Based removal of an ingredient from the cocktail that is in creation
 * @author Roland von Werden
 *
 */
@Data
public class RemoveIngredientFromEditCocktailController implements Controller {

	@Override
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse arg1) throws Exception {
		ModelAndView mav = new ModelAndView();
		// Retrieve cocktail from session
		HttpSession session = request.getSession();
		Cocktail cocktail = null;
		if(session.getAttribute("new_cocktail") != null && session.getAttribute("new_cocktail") instanceof Cocktail) {
			cocktail = (Cocktail) session.getAttribute("new_cocktail");
		}
		else {
			cocktail = new Cocktail();
			session.setAttribute("new_cocktail", cocktail);
		}
		// if the ID of the ingredient is set, try to remove it
		if (request.getParameter("id") != null) {
			try {
				long id = Long.valueOf(request.getParameter("id"));
				Ingredient ingr = null;
				// Search ingredient in the cocktail
				for (UsedIngredient ingrUsed : cocktail.getIngredientsUsed()) {
					if (ingrUsed.getIngredient().getId() == id) {
						ingr = ingrUsed.getIngredient();
					}
				}
				// If the ingredient was found, remove it from the cocktail
				if (ingr != null) {
					cocktail.removeIngredient(ingr);
				}
				mav.addObject("id", id);
			} catch (NumberFormatException e) {
				// TODO: handle exception
			}
		}
		return mav;
	}

}
